// 获取频道列表数据
async function setChannleList() {
    await axios({
        url: '/v1_0/channels'
    }).then(result => {
        console.log(result);
        const htmlStr = `<option value="">请选择频道文章</option>` + result.data.channels.map(item => {
            return `<option value="${item.id}">${item.name}</option>`
        }).join('')
        document.querySelector('.form-select').innerHTML = htmlStr
    })
}

setChannleList()

document.querySelector('.img-file').addEventListener('change', async e => {
    const file = e.target.files[0]
    const fd = new FormData()
    fd.append('image', file)
    const res = await axios({
        url: '/v1_0/upload',
        method: 'POST',
        data: fd
    })
    console.log(res);
    const imgUrl = res.data.url
    document.querySelector('.rounded').src = imgUrl
    document.querySelector('.rounded').classList.add('show')
    document.querySelector('.place').classList.add('hide')
})
// 点击图片选择新的图片上传=>模拟.img-file的input被点击之后上传
document.querySelector('.rounded').addEventListener('click', () => {
    document.querySelector('.img-file').click()
})

// 点击上传，上传表单数据
document.querySelector('.send').addEventListener('click', async e => {
    if (e.target.innerHTML !== '发布') return
    const form = document.querySelector('.art-form')
    const data = serialize(form, { hash: true, empty: true })
    //console.log(data);
    // id属性没用，删除掉
    delete data.id
    console.log(data);
    // 将收集的图片地址保存到打他对象里面
    data.cover = {
        type: 1,
        images: [document.querySelector('.rounded').src]
    }

    // 向接口发送请求
    try {
        const res = await axios({
            url: '/v1_0/mp/articles',
            method: 'POST',
            data: data
        })
        myAlert(true, '文章发布成功')
        // 重置表单并跳转到列表页面
        form.reset()
        // 封面需要手动重置
        document.querySelector('.rounded').src = ''
        document.querySelector('.rounded').classList.remove('show')
        document.querySelector('.place').classList.remove('hide')
        // 富文本编辑器重置
        editor.setHtml('')
        setTimeout(() => {
            location.href = '../content/index.html'
        }, 1500);
    } catch (error) {
        //console.dir(error)
        myAlert(false, error.response.data.message)
    }

})

    ; (function () {
        // 获取传递过来的参数
        const paramsStr = location.search
        const params = new URLSearchParams(paramsStr)
        params.forEach(async (value, key) => {
            console.log(value, key);
            if (key === 'id') {
                document.querySelector('.title span').innerHTML = '修改文章'
                document.querySelector('.send').innerHTML = '修改'
                // 文章数据回显
                const res = await axios({
                    url: `/v1_0/mp/articles/${value}`
                })
                //console.log(res);
                const dataObj = {
                    channel_id: res.data.channel_id,
                    title: res.data.title,
                    rounded: res.data.cover.images[0],
                    content: res.data.content,
                    id: res.data.id
                }
                console.log(dataObj);
                //遍历对象将数据回显到组件里
                Object.keys(dataObj).forEach((key) => {
                    // 处理长传图片
                    if (key === 'rounded') {
                        if (dataObj[key]) {
                            document.querySelector('.rounded').src = dataObj[key]
                            document.querySelector('.rounded').classList.add('show')
                            document.querySelector('.place').classList.add('hide')
                        }
                    } else if (key === 'content') {
                        // 处理富文本编辑器
                        editor.setHtml()
                        editor.setHtml(dataObj[key])
                    } else {
                        // 使用带有name字段的标签选择器作为同名绑定
                        document.querySelector(`[name=${key}]`).value = dataObj[key]
                    }
                })
            }
        })

    })();

document.querySelector('.send').addEventListener('click', async e => {
    if (e.target.innerHTML !== '修改') return
    const form = document.querySelector('.art-form')
    const data = serialize(form, { hash: true, empty: true })
    console.log(data);
    try {
        const res = await axios({
            url: `/v1_0/mp/articles/${data.id}}`,
            method: 'PUT',
            data: {
                ...data,
                cover: {
                    type: document.querySelector('.rounded').src ? 1 : 0,
                    images: [document.querySelector('.rounded').src]
                }
            }
        })
        console.log(res);
        myAlert(true, '修改文章成功')
        setTimeout(() => {
            location.href = location.href = '../content/index.html'
        }, 3000)
    } catch (error) {
        myAlert(false, error.response.data.message)
    }
})   